package com.cwises.action.system.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.core.base.BaseAction;
import com.cwises.entity.system.role.UserRoleManager;
import com.cwises.entity.system.user.UserInfoManager;
import com.cwises.service.system.user.UserService;
import com.cwises.service.system.user.UserrolemanagerService;
import com.orm.Page;
import com.util.Global;
import com.util.Util;

@Controller
public class UserAction extends BaseAction {
	@Resource(name = "userService")
	private UserService userService;
//	@Resource(name = "AopService")
//	private AopService aopService;
	@Resource(name = "userrolemanagerService")
	private UserrolemanagerService userrolemanagerService;
	
	String outPath;
	private String isReapeat;// 用户名是否存在 1存在，0不存在
	private static String result;
	private String actionResult;
	List<UserInfoManager> list = null;
	/* 当前页号及每页数 */
	private Page<UserInfoManager> page;
	private int currentPage;
	private int pageSize;
	private UserInfoManager userInfo;
	Logger log = Logger.getLogger(this.getClass());

	/**
	 * 
	 * @Title: getAllUser
	 * @Description: 获取用户列表
	 * @param @return
	 * @param @throws Exception
	 * @return String
	 * @author wangxinmin
	 * @date 2013-12-24 下午2:38:59
	 * @throws
	 */
	public String getAllUser() throws Exception {
		page = new Page<UserInfoManager>();
	    //设置每页条数
        page.setPageSize(10);
        //设置当前页
        page.setCurrentPage(currentPage);
        page=userService.findByCondition("findAll",userInfo,page);
		if(result!=null){
			actionResult=result.toString();
			result=null;
		}
		setActionResult(actionResult);
		return "success";
	}
	/**
	 * 
	 * @Title: selRole
	 * @Description: 保存用户权限
	 * @param @return
	 * @param @throws Exception
	 * @return String
	 * @author zhaojie
	 * @date 2014-1-22 上午10:03:28
	 * @throws
	 */
	public String selRole() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		List<UserRoleManager> list = new ArrayList<UserRoleManager>();
		String UserId = request.getParameter("UserId");
		String RoleId = request.getParameter("RoleId");
		String updatePerson = getCurUser().getUserId();
		String[] array;
		array = RoleId.split(",");
		for (int i = 0; i < array.length; i++) {
			UserRoleManager userRoleManager = new UserRoleManager();
			userRoleManager.setUserRoleId(UUID.randomUUID().toString());
			userRoleManager.setStatus(1);
			userRoleManager.setCreateTime(new Date());
			userRoleManager.setUpdateTime(new Date());
			userRoleManager.setUserId(UserId);
			userRoleManager.setUpdatePerson(updatePerson);
			userRoleManager.setCreatePerson(updatePerson);
			userRoleManager.setRoleName(array[i]);
			list.add(userRoleManager);
		}
		if(RoleId != null && !"".equals(RoleId)){
			userrolemanagerService.selRoleManager(list, UserId);
		}else{
			userrolemanagerService.selRoleManager(null, UserId);
		}
//		aopService.logAdd("用户管理", "保存权限", 5, "", "success".equals(result) ? 1 : 0);
		return "success";
	}
	/**
	 * 
	 * @Title: toUpdatePwd
	 * @Description: 打开修改密码
	 * @param @return
	 * @param @throws Exception
	 * @return String
	 * @throws
	 */
	public String toUpdatePwd() throws Exception {
		return "success";
	}
	public void resetPwd() throws Exception {
		String UserId = getParameter("UserId");
		String UserPwd = getParameter("UserPwd");
		String IsReserved = getParameter("IsReserved");
		if(UserPwd==null){
			UserPwd=Global.USER_PSW;
		}
		if(IsReserved==null){
			IsReserved="1";
		}else{
			IsReserved="0";
		}
		Boolean result = false;
		UserInfoManager userInfo = new UserInfoManager();
		String UpdatePerson = getCurUserId();
		userInfo.setUpdatePerson(UpdatePerson);
		userInfo.setUpdateTime(new Date());
		userInfo.setUserId(UserId);
		userInfo.setIsReserved(IsReserved);
//		对密码MD5加密
		String passWordMd5 = Util.MD5(UserPwd);
		userInfo.setUserPwd(passWordMd5);
		try {
			userService.updateByCondition("updateUserPwd", userInfo);
			result=true;
		} catch (Exception e) {
			log.error(e);
		}
//		aopService.logAdd("用户管理", "重置密码", 5, "", result ? 1 : 0);
		ServletActionContext.getResponse().getWriter().write(result?Global.USER_PSW:result.toString());
	}
	/**
	 * 
	 * @Title: validateUserPwd
	 * @Description: 验证旧密码是否正确
	 * @param @throws Exception
	 * @return void
	 * @author wangxinmin
	 * @date 2013-12-31 下午4:39:36
	 * @throws
	 */
	public void validateUserPwd() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String UserId = request.getParameter("UserId");
		String UserName = request.getParameter("UserName");
		String UserPwd = request.getParameter("UserPwd");
		//对密码MD5加密
		String passWordMd5 = Util.MD5(UserPwd);
		UserInfoManager userInfo = new UserInfoManager();
		userInfo.setUserId(UserId);
		userInfo.setUserPwd(passWordMd5);
		userInfo.setUserName(UserName);
		int count = userService.getUserInfoForUpdatePwd(userInfo);
		Boolean result = false;
		if (count > 0) {
			result = true;
		}
		ServletActionContext.getResponse().getWriter().write(result.toString());
	}
	/**
	 * 
	 * @Title: validateUser
	 * @Description: 校验用户是否存在
	 * @param @return
	 * @param @throws Exception
	 * @return String
	 * @throws
	 */
	public void validateUser() throws Exception {
		String UserId = getParameter("UserId");
		String UserName = getParameter("UserName");
		userInfo = new UserInfoManager();
		userInfo.setUserName(UserName);
		userInfo.setUserId(UserId);
		int count = (int)userService.findObjectByCondition("getUserInfoForValidate", userInfo);
		Boolean result = true;
		if (count > 0) {
			result = false;
		}
		ServletActionContext.getResponse().getWriter().write(result.toString());
	}
	/**
	 * 
	 * @Title: validateUserStatus
	 * @Description: 校验用户是否停用
	 * @param @throws Exception
	 * @return void
	 * @throws
	 */
	public void validateUserStatus() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String UserName = request.getParameter("UserName");
		String UserPwd = request.getParameter("UserPwd");
		//对密码MD5加密
		String passWordMd5 = Util.MD5(UserPwd);
		UserInfoManager userInfo = new UserInfoManager();
		userInfo.setUserPwd(passWordMd5);
		userInfo.setUserName(UserName);
		int count = (int)userService.findObjectByCondition("getUserInfoForValidateUserStatus", userInfo);
		Boolean result = false;
		if (count > 0) {
			result = true;
		}
		ServletActionContext.getResponse().getWriter().write(result.toString());
	}
	/**
	 * 
	 * @Title: deleteUser
	 * @Description: 删除用户
	 * @param @return
	 * @param @throws Exception
	 * @return String
	 * @throws
	 */
	public String deleteUser() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("UserId");
		boolean delResult = true;
		String flag = "error";
		try {
			delResult = userService.delete(id);
		} catch (Exception e) {
			log.error(e);
		}
		if (delResult) {
			flag = "success";
		} else {
			flag = "error";
		}
//		aopService.logAdd("用户管理", "删除", 5, "", "success".equals(flag) ? 1 : 0);
		result=flag;
		return flag;
	}
	   /**
     * @Title: deleteBatch
     * @Description: 批量删除
     * @return
     * @return String
     * @throws
     */
    public String deleteUserBatch() {
    	HttpServletRequest request = ServletActionContext.getRequest();
    	String ActivityIds = request.getParameter("UserId");
    	String flag = "error";
        if(ActivityIds!=null){
            try {
                String[] ids = ActivityIds.split(",");
                //对应map中deleteBatch
                userService.deleteBatch(ids);
                flag = "success";
            } catch (Exception e) {
                flag = "error";
                log.error(e);
            }
        }
        //添加日志
//        aopService.logAdd("用户管理","删除",5,"","success".equals(flag)?1:0); 
        //返回操作结果
        result=flag;
        return "success";
    }
	/**
	 * 
	 * @Title: toAddUser
	 * @Description: 跳转到添加用户页面
	 * @param @return
	 * @param @throws Exception
	 * @throws
	 */
	public String toAddUser() throws Exception {
		return "success";
	}
	/**
	 * 
	* @Title: addUser   
	* @Description: 新增用户
	* @param @return
	* @param @throws Exception      
	* @return String   
	* @throws
	 */
	public String addUser() throws Exception {
		String flag="success";
		String CreatePerson = getCurUserId();
		String passWordMd5 = Util.MD5(Global.USER_PSW);
		userInfo.setUserId(UUID.randomUUID().toString());
		userInfo.setUserPwd(passWordMd5);
		userInfo.setCreatePerson(CreatePerson);
		userInfo.setUpdatePerson(CreatePerson);
		userInfo.setCreateTime(new Date());
		userInfo.setUpdateTime(new Date());
		userInfo.setShopId(getCurUser().getShopId());
		userInfo.setStatus(1);
		try{
			userService.addUserInfoAndData(userInfo);
		}catch(Exception e){
			e.printStackTrace();
			flag="error";
		}
		result=flag;
//		aopService.logAdd("用户管理", "新增用户", 5, "", "success".equals(result) ? 1 : 0);
		return "success";
	}
	/**
	 * 
	 * @Title: modifyUser
	 * @Description:修改用户
	 * @param @return
	 * @param @throws Exception
	 * @return String
	 * @throws
	 */
	public String modifyUser() throws Exception {
		String id = getParameter("UserId");
		UserInfoManager userInfo = (UserInfoManager) userService.findById(id);
		setUserInfo(userInfo);
		return "success";
	}
	/**
	 * 
	* @Title: modifyUser   
	* @Description: 首页修改用户
	* @param @return
	* @param @throws Exception      
	* @return String   
	* @throws
	 */
	public String modifyHomeUser() throws Exception {
		String id=getCurUser().getUserId();
		UserInfoManager userInfo = (UserInfoManager) userService.findById(id);
		setUserInfo(userInfo);
		if(result!=null){
			actionResult=result.toString();
			result=null;
		}
		setActionResult(actionResult);
		return "success";
	}
	/**
	 * 
	* @Title: updateUser   
	* @Description: 修改用户信息 
	* @param @return
	* @param @throws Exception      
	* @return String   
	* @throws
	 */
	public String updateUser() throws Exception {
		String flag = "success";
		UserInfoManager curUser=getCurUser();
		String UpdatePerson = curUser.getUserId();
		String UserId = userInfo.getUserId();
		userInfo.setUpdatePerson(UpdatePerson);
		userInfo.setUpdateTime(new Date());
		userInfo.setSex(curUser.getShopId());
		try {
			userService.updateUser(userInfo);
		} catch (Exception e) {
			flag = "error";
			log.error(e);
		}
		//如果是修改当前登录人信息，修改缓存
		if(UpdatePerson.equals(UserId)){
			userInfo.setIsAdmin(curUser.getIsAdmin());
			setCurUser(userInfo);
		}
//		aopService.logAdd("用户管理", "修改", 5, "updateUser","success".equals(flag) ? 1 : 0);
		result=flag;
		return flag;
	}
	
	/**
	 * @Description: 跳转到分配账号页面（未使用，保留）
	 * @return
	 * @throws Exception
	 */
	
	public String toAddAccount() throws Exception {
		return "success";
	}
	/**
	 * 
	 * @Title: addUserAccount
	 * @Description: 人员分配账号,向userinfo表里面添加(未使用)
	 * @param @return
	 * @param @throws Exception
	 * @return String
	 * @author lishanhe
	 * @date 2013-12-31 下午4:16:34
	 * @throws
	 */
	public String addAccount() throws Exception {
		String flag="success";
		String CreatePerson = getCurUserId();
		String passWordMd5 = Util.MD5(Global.USER_PSW);
		userInfo.setUserId(UUID.randomUUID().toString());
		userInfo.setUserPwd(passWordMd5);
		userInfo.setCreatePerson(CreatePerson);
		userInfo.setUpdatePerson(CreatePerson);
		userInfo.setCreateTime(new Date());
		userInfo.setUpdateTime(new Date());
		userInfo.setStatus(1);
		userInfo.setShopId(getCurUser().getShopId());
		try{
			userService.addUserInfoAndData(userInfo);
		}catch(Exception e){
			flag="error";
		}
		result=flag;
//		aopService.logAdd("用户管理", "新增用户", 5, "", "success".equals(result) ? 1 : 0);
		return "success";
	}
	/**
	 * 
	 * @Title: changeStatus
	 * @Description: 更换状态
	 * @param @throws Exception
	 * @return void
	 * @throws
	 */
	public void changeStatus() throws Exception {
		String UserId = getParameter("UserId");
		String UserStatus = getParameter("UserStatus");
		Boolean result = true;
		UserInfoManager userInfo = new UserInfoManager();
		String UpdatePerson = getCurUserId();
		userInfo.setUpdatePerson(UpdatePerson);
		userInfo.setUpdateTime(new Date());
		userInfo.setUserId(UserId);
		userInfo.setStatus(Integer.parseInt(UserStatus));
		try {
			userService.updateByCondition("changeStatus", userInfo);
		} catch (Exception e) {
			log.error(e);
			result=false;
		}
//		aopService.logAdd("用户管理", "更换状态", 5, "", result ? 1 : 0);
		ServletActionContext.getResponse().getWriter().write(result.toString());
	}

	/**
	 * @return the currentPage
	 */
	public int getCurrentPage() {
		return currentPage;
	}

	/**
	 * @param currentPage
	 *            the currentPage to set
	 */
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	/**
	 * @return the pageSize
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * @param pageSize
	 *            the pageSize to set
	 */
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	/**
	 * @return the isReapeat
	 */
	public String getIsReapeat() {
		return isReapeat;
	}

	/**
	 * @param isReapeat
	 *            the isReapeat to set
	 */
	public void setIsReapeat(String isReapeat) {
		this.isReapeat = isReapeat;
	}

	/**
	 * @return the actionResult
	 */
	public String getActionResult() {
		return actionResult;
	}

	/**
	 * @param actionResult
	 *            the actionResult to set
	 */
	public void setActionResult(String actionResult) {
		this.actionResult = actionResult;
	}

	/**
	 * @return the userInfo
	 */
	public UserInfoManager getUserInfo() {
		return userInfo;
	}

	/**
	 * @param userInfo
	 *            the userInfo to set
	 */
	public void setUserInfo(UserInfoManager userInfo) {
		this.userInfo = userInfo;
	}


	public List<UserInfoManager> getList() {
		return list;
	}

	public void setList(List<UserInfoManager> list) {
		this.list = list;
	}

	public Page<UserInfoManager> getPage() {
		return page;
	}

	public void setPage(Page<UserInfoManager> page) {
		this.page = page;
	}

}
